package org.blog.service;

import java.util.List;

import org.blog.dao.AdvertDao;
import org.blog.helper.Result;
import org.blog.model.ActionType;
import org.blog.model.ModelAdvert;
import org.blog.model.ModelPassport;
import org.blog.service.util.ServiceConstants;
import org.blog.service.util.ValidateHelper;
import org.springframework.beans.factory.annotation.Autowired;

public class AdvertServiceImpl implements AdvertService {

	@Autowired
	private AdvertDao advertDao;

	@Override
	public Result<?> addAdvert(ModelAdvert t, ModelPassport passport) {
		if (passport != null && passport.getRole() >= ServiceConstants.ADMIN) {
			if (ValidateHelper.validate(t, ActionType.ADD)) {
				t.setUsername(passport.getUsername());
				t.setCreateTime(System.currentTimeMillis()/1000);
				advertDao.addAdvert(t);
				return new Result<Object>(200);
			} else {
				return new Result<Object>(400);
			}
		} else {
			return new Result<Object>(401);
		}
	}

	@Override
	public Result<?> modifyAdvert(ModelAdvert t, ModelPassport passport) {
		if (passport != null && passport.getRole() >= ServiceConstants.ADMIN) {
			if (ValidateHelper.validate(t, ActionType.MODIFY)) {
				t.setUsername(passport.getUsername());
				advertDao.modifyAdvert(t);
				return new Result<Object>(200);
			} else {
				return new Result<Object>(400);
			}
		} else {
			return new Result<Object>(401);
		}
	}

	@Override
	public Result<ModelAdvert> getAdvert(ModelAdvert t, ModelPassport passport) {
		if (passport != null && passport.getRole() >= ServiceConstants.ADMIN) {
			if (ValidateHelper.validate(t, ActionType.GET)) {
				ModelAdvert advert = advertDao.getAdvert(t.getId());
				return new Result<ModelAdvert>(advert, 200);
			} else {
				return new Result<ModelAdvert>(400);
			}
		} else {
			return new Result<ModelAdvert>(401);
		}
	}

	@Override
	public Result<List<ModelAdvert>> getList(ModelPassport passport) {
		if (passport != null && passport.getRole() >= ServiceConstants.ADMIN) {
			List<ModelAdvert> list = advertDao.getList();
			return new Result<List<ModelAdvert>>(list, 200);
		} else {
			return new Result<List<ModelAdvert>>(401);
		}
	}

}
